package com.example.servlet;

import com.example.Service.CommentService;
import com.example.pojo.Comment;
import com.google.gson.Gson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "GetCommentByNewsIdServlet", value = "/GetCommentByNewsIdServlet")
public class GetCommentByNewsIdServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> result = new HashMap<>();

        try {
            int newsId = Integer.parseInt(request.getParameter("newsId"));
            String userId = request.getParameter("userId"); // 接收前端传递的 userId
            CommentService commentService = new CommentService();
            // 调用带 userId 的方法，获取含 isLiked 的评论列表
            List<Comment> commentList = commentService.getCommentByNewsId(newsId, userId);

            result.put("code", 200);
            result.put("msg", "查询成功");
            result.put("length", commentList.size());
            result.put("data", commentList); // 此时 data 中的每个评论都有 isLiked 字段
        } catch (NumberFormatException e) {
            result.put("code", 400);
            result.put("msg", "参数错误（newsId 必须为数字）");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "查询失败：" + e.getMessage());
        }

        new Gson().toJson(result, response.getWriter());
    }
}